package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.addSetmeal(setmeal);
        Integer setmealId = setmeal.getId();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        //添加关系
        if(checkgroupIds != null && checkgroupIds.length > 0){
            for (Integer checkgroupId : checkgroupIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("setmealId",setmealId);
                map.put("checkgroupId",checkgroupId);
                setmealDao.setSetmealAndCheckGroup(map);
            }
        }

        //生成模板
        generateMobileStaticHtml();
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {

        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        PageHelper.startPage(currentPage,pageSize);
        String queryString = queryPageBean.getQueryString();
        Page<Setmeal> page = setmealDao.findPage(queryString);
        long total = page.getTotal();
        List<Setmeal> result = page.getResult();
        return new PageResult(total,result);
    }

    //回显数据
    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setmealDao.findById(id);
        String img = setmeal.getImg();
        String newimg = img;
        setmeal.setImg(newimg);
        return setmeal;
    }

    @Override
    public List<Integer> findCheckgroupIdsByCheckGroupId(Integer id) {

        return setmealDao.findCheckgroupIdsByCheckGroupId(id);
    }

    //编辑套餐
    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        String newImg = setmeal.getImg();
        if(!StringUtils.isEmpty(newImg)){
            Setmeal setmea = setmealDao.findById(setmeal.getId());
            String worNimg = setmea.getImg();
            if(!worNimg.equals(newImg)){
                //先删除旧的图片
                QiniuUtils.deleteFileFromQiniu(worNimg);
                //删除set集合里的图片
                jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_RESOURCES,worNimg);
                jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES,worNimg);
                // //添加新图到缓存中
                jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,newImg);
            }
        }
        //删除旧的检查组重新添加
        setmealDao.deleteBySetmealId(setmeal.getId());

        if(checkgroupIds != null && checkgroupIds.length >0){
            for (Integer checkgroupId : checkgroupIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("setmealId",setmeal.getId());
                map.put("checkgroupId",checkgroupId);
                setmealDao.setSetmealAndCheckgroup(map);
            }
        }

        //修改套餐
        setmealDao.upDateBySetmeal(setmeal);

        //生成模板
        generateMobileStaticHtml();
    }

    //删除
    @Override
    public void deleteBySetmeal(Integer id) {
        Setmeal setmeal = setmealDao.findById(id);
        String img = setmeal.getImg();
        //七牛云删除图片
        QiniuUtils.deleteFileFromQiniu(img);
        //删除缓存数据
        jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_RESOURCES,img);
        jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES,img);
        //删除关系列表
        setmealDao.deleteBySetmealId(id);
        //删除套餐
        setmealDao.delete(id);
        //删除页面
        File file = new File("F:\\ideaProjects\\health\\health_parent\\health_mobile\\src\\main\\webapp\\pages\\setmeal_detail_"+id+".html");
        file.delete();
        //生成模板
        generateMobileStaticHtml();

    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    //通过套餐id查检查组和检查项的信息
    @Override
    public Setmeal findByIdCheckgroupAndCheckitem(Integer id) {
        return setmealDao.findByIdCheckgroupAndCheckitem(id);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        List<Map<String, Object>> list = new ArrayList<>();
        //查询所有套餐
        List<Setmeal> setmeals = setmealDao.findAll();
        for (Setmeal setmeal : setmeals) {
            Map<String, Object> map = new HashMap<>();
            map.put("name",setmeal.getName());
            //查询预约人数通过套餐名称
           Integer count = setmealDao.findBySetmealName(setmeal.getName());
            map.put("value",count);
            list.add(map);
        }
        return list;
    }


    //生成静态页面
    public void generateMobileStaticHtml() {

        //获取数据
        List<Setmeal> setmealList = setmealDao.findAll();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成详情信息包含检查组检查项
        generateMobileSetmealDetailHtml(setmealList);

    }
    //生成套餐列表静态页面
    private void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        //准备数据
        Map map = new HashMap();
        map.put("setmealList",setmealList);
        //调用模板
        generateHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    //生成详情信息包含检查组检查项
    private void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        //准备数据
        for (Setmeal setmeal : setmealList) {
            Map map = new HashMap();
            Setmeal setme = setmealDao.findByIdCheckgroupAndCheckitem(setmeal.getId());
            map.put("setmeal",setme);
            generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
        }
    }



    //调用创建出静态模板
    public void generateHtml(String templateName,String htmlPageName,Map map){
        //加载模板文件
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer writer = null;
        try {
            //指定模板
            Template template = configuration.getTemplate(templateName);
            //设置Writer对象
            writer = new FileWriter(new File(outPutPath + "/" +htmlPageName));
            template.process(map,writer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(writer != null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
